<?php

namespace app\admin\controller;

use app\common\model\AdminForm;
use think\App;
use think\facade\Db;
use think\facade\View;
use util\Curd;

class FlyDesigner extends Base
{
    protected $middleware = ['AdminCheck', 'AutoMakePermission'];
    protected $event = null;
    protected $info = [];
    protected $fid = 0;

    public function initialize()
    {
        $this->fid = input('param.id');
        $this->info = AdminForm::where('id', $this->fid)->find();

        $eventName = 'app\\common\\flydesigner\\' . underline_hump($this->info['table']) . 'Event';
        if (class_exists($eventName)) {
            $this->event = new $eventName();
        }
    }

    public function index()
    {
        if (request()->isAjax()) {

            $result = Curd::autoShowData($this->info);

            // 重新整理参数 HOOK
            if (is_callable([$this->event, 'redoListParam'])) {
                $result = $this->event->redoListParam($result);
            }

            return json(pageReturn(['code' => 0, 'data' => $result, 'msg' => 'success']));
        }

        if ($this->info['status'] == 1) {
            $this->error('该功能已经被卸载', '/');
        }

        list($tableDict, $relationDict, $showMap, $field, $searchMap, $where) = Curd::parseIndexTpl($this->info);

        return $this->fetch('', [
            'id' => $this->fid,
            'cols' => json_encode($showMap),
            'search' => $searchMap
        ]);
    }

    public function add()
    {
        if (request()->isPost()) {

            $eventData = $param = input('post.');

            // 重新整理参数 HOOK
            if (is_callable([$this->event, 'redoAddParam'])) {
                $param = $this->event->redoAddParam($param);
            }

            $tableJson = json_decode($this->info['form_json'], true);
            $rule = Curd::makeSimpleCheckRule($tableJson);
            unset($param['id']);

            $validate = \think\facade\Validate::rule($rule);
            if (!$validate->check($param)) {
                return jsonReturn(-1, $validate->getError());
            }

            // 新增操作之前的 HOOK
            if (is_callable([$this->event, 'beforeAdd'])) {
                $res = $this->event->beforeAdd($eventData);
                if ($res['code'] != 0) {
                    return json($res);
                }
            }

            // 入库
            $param['create_time'] = date('Y-m-d H:i:s');
            // 兼容上传组件多余的字段
            if (isset($param['file'])) {
                unset($param['file']);
            }

            try {

                foreach ($param as $key => $vo) {
                    if (is_array($vo)) {
                        $param[$key] = implode(',', $vo);
                    }
                }

                $insertId = Db::name($this->info['table'])->insertGetId($param);
            } catch (\Exception $e) {
                return jsonReturn(-3, $e->getMessage());
            }

            // 新增操作之后的 HOOK
            $eventData['data_id'] = $insertId;
            if (is_callable([$this->event, 'afterAdd'])) {
                $res = $this->event->afterAdd($eventData);
                if ($res['code'] != 0) {
                    return json($res);
                }
            }

            return jsonReturn(0, '新增成功');
        }

        $formJson = parseJson(json_decode($this->info['form_json'], true));
        View::assign('id', $this->fid);
        View::assign('data', empty($formJson) ? '[]' : json_encode($formJson));

        return $this->fetch();
    }

    public function edit()
    {
        $dataId = input('param.data_id');

        if (request()->isPost()) {

            $eventData = $param = input('post.');

            // 重新整理参数 HOOK
            if (is_callable([$this->event, 'redoEditParam'])) {
                $param = $this->event->redoEditParam($param);
            }

            $tableJson = json_decode($this->info['form_json'], true);
            $rule = Curd::makeSimpleCheckRule($tableJson);
            unset($param['id'], $param['data_id']);

            $validate = \think\facade\Validate::rule($rule);
            if (!$validate->check($param)) {
                return jsonReturn(-1, $validate->getError());
            }

            // 更新操作之前的 HOOK
            if (is_callable([$this->event, 'beforeUpdate'])) {
                $res = $this->event->beforeUpdate($eventData);
                if ($res['code'] != 0) {
                    return json($res);
                }
            }

            // 更新
            $param['update_time'] = date('Y-m-d H:i:s');
            // 兼容上传组件多余的字段
            if (isset($param['file'])) {
                unset($param['file']);
            }

            try {

                foreach ($param as $key => $vo) {
                    if (is_array($vo)) {
                        $param[$key] = implode(',', $vo);
                    }
                }

                Db::name($this->info['table'])->where('id', $dataId)->update($param);
            } catch (\Exception $e) {
                return jsonReturn(-3, $e->getMessage());
            }

            // 更新操作之后的 HOOK
            if (is_callable([$this->event, 'afterUpdate'])) {
                $res = $this->event->afterUpdate($eventData);
                if ($res['code'] != 0) {
                    return json($res);
                }
            }

            return jsonReturn(0, '编辑成功');
        }

        $formJson = parseJson(json_decode($this->info['form_json'], true));
        $dataInfo = Db::name($this->info['table'])->where('id', $dataId)->find();
        // 初始值
        foreach ($formJson as $key => $vo) {
            if (!isset($dataInfo[$vo['field']])) {
                continue;
            }

            if (in_array($vo['tag'], ['select', 'radio', 'checkbox'])) {
                if ($vo['datasourceType'] == 'local') {
                    foreach ($vo['options'] as $k => $v) {
                        if (in_array($v['value'], explode(',', $dataInfo[$vo['field']]))) {
                            $formJson[$key]['options']['checked'] = true;
                        }
                    }
                } else {
                    if ($vo['tag'] == 'checkbox') {
                        $formJson[$key]['remoteDefaultValue'] = explode(',', $dataInfo[$vo['field']]);
                    } else {
                        $formJson[$key]['remoteDefaultValue'] = $dataInfo[$vo['field']];
                    }
                }
            } else {
                $formJson[$key]['defaultValue'] = $dataInfo[$vo['field']];
            }
        }

        View::assign('id', $this->fid);
        View::assign('data_id', $dataId);
        View::assign('data', empty($formJson) ? '[]' : json_encode($formJson));

        return $this->fetch();
    }

    public function del()
    {
        $dataId = input('post.data_id');

        // 删除操作之前的 HOOK
        if (is_callable([$this->event, 'beforeDel'])) {
            $res = $this->event->beforeDel($dataId);
            if ($res['code'] != 0) {
                return json($res);
            }
        }

        try {
            Db::name($this->info['table'])->where('id', $dataId)->delete();
        } catch (\Exception $e) {
            return jsonReturn(-2, $e->getMessage());
        }

        // 删除操作之后的 HOOK
        if (is_callable([$this->event, 'afterDel'])) {
            $res = $this->event->afterDel($dataId);
            if ($res['code'] != 0) {
                return json($res);
            }
        }

        return jsonReturn(0, '删除成功');
    }

    public function version()
    {
        return jsonReturn(0, '当前版本', config('version.version'));
    }
}